package com.osdp.uc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.osdp.common.constant.CommonConstant;
import com.osdp.common.exception.PlatformException;
import com.osdp.common.http.Result;
import com.osdp.common.util.MessageUtil;
import com.osdp.uc.service.IUcUserService;
import com.osdp.uc.vo.UcUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@Api(tags = "用户信息")
@RestController
//@RefreshScope
@RequestMapping("/uc/user")
public class UcUserController {

    @Autowired
    private IUcUserService ucUserService;
    /**
     * @RequestParam 参数形式： /emp?pageNo=2&param2=20 是从request里面拿取值
     * @PathVariable 参数形式：/emp/2 是从一个URI模板里面来填充，为了实现RestFul的风格,/emp/{id}/{name}
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<UcUserVo>> pageList(
            UcUserVo userVo,
            @RequestParam(name = "pageNo", defaultValue = "1") int pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize){
        IPage<UcUserVo> result = ucUserService.pageList(userVo,new Page<>(pageNo, pageSize));
        return Result.success(result);
    }

    @RequestMapping(value = "/pageList", method = RequestMethod.GET)
    public IPage<UcUserVo> pageListByOrgId( UcUserVo userVo,
        @RequestParam(name = "pageNo", defaultValue = "1") int pageNo,
        @RequestParam(name = "pageSize", defaultValue = "10") int pageSize){
        return ucUserService.pageListByOrgId(userVo,new Page<>(pageNo, pageSize));
    }

    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    public Result<UcUserVo> getById(
            @RequestParam(name = "id", required = true) String id,
            @RequestParam(name = "orgId", required = false) String orgId){
        UcUserVo userVo = ucUserService.getByUserId(id,orgId);
        return Result.success(userVo);
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ApiOperation("新增用户")
    public Result insert(@RequestBody JSONObject jsonObject) {
        boolean isSuccess = false;
        try {
            UcUserVo userVo = JSON.parseObject(jsonObject.toJSONString(), UcUserVo.class);
            isSuccess = ucUserService.insertUser(userVo);
        }catch (PlatformException e) {
            return Result.fail(e.getMessage());
        }
        return (isSuccess)? Result.success():Result.fail();
      }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    @ApiOperation("编辑用户")
    public Result update(@RequestBody JSONObject jsonObject) {
        boolean isSuccess = false;
//        List<String> roles = jsonObject.getJSONArray("roles").toJavaList(String.class);
//        UcUserVo userVo = jsonObject.getJSONObject("user").toJavaObject(UcUserVo.class);
        try {
            UcUserVo userVo = JSON.parseObject(jsonObject.toJSONString(), UcUserVo.class);
//            String roles = jsonObject.getString("selectedroles");
            isSuccess = ucUserService.updateUser(userVo);//roles
        }catch (PlatformException e) {
            return Result.fail(e.getMessage());
        }
        return  (isSuccess)? Result.success():Result.fail();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ApiOperation(value = "删除用户")
    public Result delete(@RequestParam(name = "id", required = true) String id,
                         @RequestParam(name = "orgId", required = true) String orgId) {
        if(StringUtils.isEmpty(id)) {
            return Result.fail(MessageUtil.getMessage(10051));
        }
        boolean isOk = ucUserService.deleteUser(id, orgId);
        return isOk ? Result.success(MessageUtil.getMessage(10049)) : Result.fail(MessageUtil.getMessage(10051));
    }

    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    @ApiOperation("批量删除用户")
    public Result deleteBatcah(@RequestBody JSONObject jsonObject){
        String ids = jsonObject.getString("ids");
        String orgId = jsonObject.getString("orgId");
        if(StringUtils.isEmpty(ids)) {
            return Result.fail(MessageUtil.getMessage(10051));
        }
        boolean isOk = ucUserService.deleteBatcah(Arrays.asList(StringUtils.split(ids, ",")),orgId);
        return isOk ? Result.success(MessageUtil.getMessage(10049)) : Result.fail(MessageUtil.getMessage(10051));
    }

    /**
     * 冻结&解冻用户
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
    public boolean frozenBatch(@RequestBody JSONObject jsonObject) {
        String ids = jsonObject.getString("ids");
        String status = jsonObject.getString("status");
        String[] arr = ids.split(",");
        return ucUserService.updateValidation(arr, status);
    }

    /**
     * 重置密码
     */
    @RequestMapping(value = "/resetPwd", method = RequestMethod.GET)
    public boolean resetPassword(@RequestParam(name = "id", required = true) String id) {
        return ucUserService.updatePassWord(id, CommonConstant.INIT_PASSWORD);
    }
//	@Autowired
//	DiscoveryClient client;
//
//	@Value("${server.port}")
//	String port;
//
//	@RequestMapping("/hello")
//	public String hello() {
//		List<ServiceInstance> instances = client.getInstances("micro-server");
//		System.out.println("------: "+ instances.size());
//		ServiceInstance selectedInstance = instances
//				.get(new Random().nextInt(instances.size()));//x在nextInt(x)方法中    必须大于等于0；
//		return "Hello World: " + selectedInstance.getServiceId() + ":" + selectedInstance
//				.getHost() + ":" + selectedInstance.getPort();
//	}
//
//	@RequestMapping(value="/index", method = RequestMethod.GET)
//    public String index(@RequestParam(name="name") String name) {
//        return "hello "+name+",this is first messge";
//    }
//
//	@RequestMapping(value="/insertUser", method = RequestMethod.POST)
//	public ResultBean<Integer> inserUser(@RequestBody UcUserVo userVo) {
//		System.out.println("---------userVo: "+ userVo.getId());
//		ResultBean<Integer> result = new ResultBean<Integer>();
//		result.setResult(userVo.getId());
//		result.setSuccess(true);
//		return result;
//	}
}
